import { devtool } from "../devtool"
import { LoaderCachePlugin } from "../Plugins/LoaderCache"

export class BaseLoader {

    plugins = {
        // $ 缓存插件
        cachePlugin: null,
    }

    
    parse(data: any): void {
        throw new Error("该函数需要父类重写")    
    }

    async load(url: string): Promise<any> {
        if (this.plugins.cachePlugin) {
          return new Promise(async (resolve, reject) => {
            const plugin = this.plugins.cachePlugin as LoaderCachePlugin
            const res = (await plugin.get(url)) as string
            if (res) {
              this.parse(JSON.parse(res))
              devtool.success("load from cache")
              resolve(this)
            } else {
              await this.fetchFromUrl(url)
              resolve(this)
            }
          })
        }
        return this.fetchFromUrl(url)
      }

      fetchFromUrl(url: string) {
        return fetch(url, { mode: "cors" })
          .then((response: any) => response.text())
          .then((data: any) => {
            if (this.plugins.cachePlugin) {
              const plugin = this.plugins.cachePlugin as LoaderCachePlugin
              plugin.set(url, data)
            }
            this.parse(JSON.parse(data))
            return this
          })
      }
}